/**
 * 认证相关 API 服务
 */

import { http } from '@/utils/request'
import type {
  LoginRequest,
  LoginResponse,
  RegisterRequest,
  ResetPasswordRequest,
  SendCodeRequest,
  RefreshTokenRequest,
  UserInfo
} from '@/types'
import { ApiEndpoints } from '@/types'

/**
 * 认证服务类
 */
export class AuthService {
  /**
   * 用户登录
   */
  static async login(data: LoginRequest): Promise<LoginResponse> {
    return http.post<LoginResponse>(ApiEndpoints.LOGIN, data)
  }

  /**
   * 用户注册
   */
  static async register(data: RegisterRequest): Promise<void> {
    return http.post<void>(ApiEndpoints.REGISTER, data)
  }

  /**
   * 用户登出
   */
  static async logout(): Promise<void> {
    return http.post<void>(ApiEndpoints.LOGOUT)
  }

  /**
   * 刷新访问令牌
   */
  static async refreshToken(refreshToken: string): Promise<LoginResponse> {
    const data: RefreshTokenRequest = { refreshToken }
    return http.post<LoginResponse>(ApiEndpoints.REFRESH, data)
  }

  /**
   * 发送验证码
   */
  static async sendVerificationCode(data: SendCodeRequest): Promise<void> {
    return http.post<void>(ApiEndpoints.SEND_CODE, data)
  }

  /**
   * 重置密码
   */
  static async resetPassword(data: ResetPasswordRequest): Promise<void> {
    return http.post<void>(ApiEndpoints.RESET_PASSWORD, data)
  }

  /**
   * 验证令牌有效性
   */
  static async validateToken(): Promise<boolean> {
    try {
      await http.get<void>(ApiEndpoints.VALIDATE)
      return true
    } catch (error) {
      return false
    }
  }

  /**
   * 获取当前用户信息
   */
  static async getUserInfo(): Promise<UserInfo> {
    return http.get<UserInfo>(ApiEndpoints.USER_INFO)
  }

  /**
   * 更新用户信息
   */
  static async updateUserInfo(data: Partial<UserInfo>): Promise<UserInfo> {
    return http.put<UserInfo>('/auth/user-info', data)
  }

  /**
   * 修改密码
   */
  static async changePassword(data: {
    oldPassword: string
    newPassword: string
    confirmPassword: string
  }): Promise<void> {
    return http.post<void>('/auth/change-password', data)
  }

  /**
   * 绑定手机号
   */
  static async bindPhone(data: {
    phone: string
    verifyCode: string
  }): Promise<void> {
    return http.post<void>('/auth/bind-phone', data)
  }

  /**
   * 绑定邮箱
   */
  static async bindEmail(data: {
    email: string
    verifyCode: string
  }): Promise<void> {
    return http.post<void>('/auth/bind-email', data)
  }

  /**
   * 解绑手机号
   */
  static async unbindPhone(data: {
    verifyCode: string
  }): Promise<void> {
    return http.post<void>('/auth/unbind-phone', data)
  }

  /**
   * 解绑邮箱
   */
  static async unbindEmail(data: {
    verifyCode: string
  }): Promise<void> {
    return http.post<void>('/auth/unbind-email', data)
  }

  /**
   * 获取用户权限列表
   */
  static async getUserPermissions(): Promise<string[]> {
    return http.get<string[]>('/auth/permissions')
  }

  /**
   * 检查用户是否有指定权限
   */
  static async hasPermission(permission: string): Promise<boolean> {
    try {
      const permissions = await this.getUserPermissions()
      return permissions.includes(permission)
    } catch (error) {
      return false
    }
  }

  /**
   * 获取用户角色列表
   */
  static async getUserRoles(): Promise<string[]> {
    return http.get<string[]>('/auth/roles')
  }

  /**
   * 检查用户是否有指定角色
   */
  static async hasRole(role: string): Promise<boolean> {
    try {
      const roles = await this.getUserRoles()
      return roles.includes(role)
    } catch (error) {
      return false
    }
  }

  /**
   * 上传头像
   */
  static async uploadAvatar(file: File): Promise<string> {
    const formData = new FormData()
    formData.append('avatar', file)
    
    return http.post<string>('/auth/upload-avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  /**
   * 删除账户
   */
  static async deleteAccount(data: {
    password: string
    verifyCode: string
  }): Promise<void> {
    return http.post<void>('/auth/delete-account', data)
  }

  /**
   * 获取登录历史
   */
  static async getLoginHistory(params?: {
    page?: number
    size?: number
  }): Promise<{
    records: Array<{
      id: string
      ip: string
      location: string
      device: string
      browser: string
      loginTime: string
      status: 'success' | 'failed'
    }>
    total: number
  }> {
    return http.get('/auth/login-history', { params })
  }

  /**
   * 清除其他设备登录状态
   */
  static async clearOtherSessions(): Promise<void> {
    return http.post<void>('/auth/clear-other-sessions')
  }

  /**
   * 启用/禁用两步验证
   */
  static async toggleTwoFactorAuth(enable: boolean): Promise<{
    qrCode?: string
    backupCodes?: string[]
  }> {
    return http.post(`/auth/two-factor/${enable ? 'enable' : 'disable'}`)
  }

  /**
   * 验证两步验证码
   */
  static async verifyTwoFactorCode(code: string): Promise<void> {
    return http.post<void>('/auth/verify-two-factor', { code })
  }
}

// 导出默认实例
export const authService = AuthService

// 便捷方法导出
export const {
  login,
  register,
  logout,
  refreshToken,
  sendVerificationCode,
  resetPassword,
  validateToken,
  getUserInfo,
  updateUserInfo,
  changePassword,
  bindPhone,
  bindEmail,
  unbindPhone,
  unbindEmail,
  getUserPermissions,
  hasPermission,
  getUserRoles,
  hasRole,
  uploadAvatar,
  deleteAccount,
  getLoginHistory,
  clearOtherSessions,
  toggleTwoFactorAuth,
  verifyTwoFactorCode
} = AuthService
